package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Tag(name = "文件上传", description = "文件上传相关的API接口")
public class FileUploadController {

    private static final String UPLOAD_DIR = "uploads/";
    private static final String IMAGE_DIR = "uploads/images/";
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final List<String> ALLOWED_IMAGE_TYPES = List.of(
        "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"
    );
    private static final List<String> ALLOWED_DOCUMENT_TYPES = List.of(
        "application/pdf", "application/msword", 
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );

    @PostMapping
    @Operation(summary = "通用文件上传")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (file.getSize() > MAX_FILE_SIZE) {
                response.put("success", false);
                response.put("message", "文件大小不能超过10MB");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 创建上传目录
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String uniqueFilename = timestamp + "_" + UUID.randomUUID().toString().substring(0, 8) + fileExtension;
            
            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回成功响应
            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("data", Map.of(
                "id", System.currentTimeMillis(),
                "filename", uniqueFilename,
                "originalName", originalFilename,
                "size", file.getSize(),
                "contentType", file.getContentType(),
                "url", "/uploads/" + uniqueFilename,
                "uploadTime", LocalDateTime.now().toString()
            ));
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PostMapping("/image")
    @Operation(summary = "图片上传")
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "图片文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (file.getSize() > MAX_FILE_SIZE) {
                response.put("success", false);
                response.put("message", "图片大小不能超过10MB");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !ALLOWED_IMAGE_TYPES.contains(contentType)) {
                response.put("success", false);
                response.put("message", "不支持的图片格式，仅支持: JPG, PNG, GIF, WebP");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 创建图片上传目录
            Path uploadPath = Paths.get(IMAGE_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String uniqueFilename = "img_" + timestamp + "_" + UUID.randomUUID().toString().substring(0, 8) + fileExtension;
            
            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回成功响应
            response.put("success", true);
            response.put("message", "图片上传成功");
            response.put("data", Map.of(
                "id", System.currentTimeMillis(),
                "filename", uniqueFilename,
                "originalName", originalFilename,
                "size", file.getSize(),
                "contentType", contentType,
                "url", "/uploads/images/" + uniqueFilename,
                "thumbnailUrl", "/uploads/images/thumb_" + uniqueFilename,
                "uploadTime", LocalDateTime.now().toString()
            ));
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "图片上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PostMapping("/batch")
    @Operation(summary = "批量文件上传")
    public ResponseEntity<Map<String, Object>> uploadBatchFiles(@RequestParam("files") MultipartFile[] files) {
        Map<String, Object> response = new HashMap<>();
        
        if (files == null || files.length == 0) {
            response.put("success", false);
            response.put("message", "没有选择文件");
            return ResponseEntity.badRequest().body(response);
        }
        
        if (files.length > 10) {
            response.put("success", false);
            response.put("message", "一次最多只能上传10个文件");
            return ResponseEntity.badRequest().body(response);
        }
        
        List<Map<String, Object>> uploadedFiles = new java.util.ArrayList<>();
        List<String> errors = new java.util.ArrayList<>();
        
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            try {
                if (file.isEmpty()) {
                    errors.add("文件 " + (i + 1) + " 为空");
                    continue;
                }
                
                if (file.getSize() > MAX_FILE_SIZE) {
                    errors.add("文件 " + (i + 1) + " 大小超过限制");
                    continue;
                }
                
                // 创建上传目录
                Path uploadPath = Paths.get(UPLOAD_DIR);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                
                // 生成唯一文件名
                String originalFilename = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                }
                
                String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
                String uniqueFilename = timestamp + "_" + UUID.randomUUID().toString().substring(0, 8) + fileExtension;
                
                // 保存文件
                Path filePath = uploadPath.resolve(uniqueFilename);
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                
                // 添加到成功列表
                uploadedFiles.add(Map.of(
                    "id", System.currentTimeMillis() + i,
                    "filename", uniqueFilename,
                    "originalName", originalFilename,
                    "size", file.getSize(),
                    "contentType", file.getContentType(),
                    "url", "/uploads/" + uniqueFilename,
                    "uploadTime", LocalDateTime.now().toString()
                ));
                
            } catch (IOException e) {
                errors.add("文件 " + (i + 1) + " 上传失败: " + e.getMessage());
            }
        }
        
        response.put("success", uploadedFiles.size() > 0);
        response.put("message", String.format("成功上传 %d 个文件，失败 %d 个", uploadedFiles.size(), errors.size()));
        response.put("data", Map.of(
            "uploadedFiles", uploadedFiles,
            "errors", errors,
            "successCount", uploadedFiles.size(),
            "errorCount", errors.size()
        ));
        
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除文件")
    public ResponseEntity<Map<String, Object>> deleteFile(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        // 这里应该根据文件ID删除文件
        // 暂时返回成功响应
        response.put("success", true);
        response.put("message", "文件删除成功");
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/list")
    @Operation(summary = "获取文件列表")
    public ResponseEntity<Map<String, Object>> getFileList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type) {
        
        // 这里应该返回文件列表，暂时返回示例数据
        List<Map<String, Object>> files = List.of(
            Map.of(
                "id", 1L,
                "filename", "20241115_143022_abc12345.jpg",
                "originalName", "product_image.jpg",
                "size", 245760,
                "contentType", "image/jpeg",
                "url", "/uploads/images/20241115_143022_abc12345.jpg",
                "uploadTime", "2024-11-15T14:30:22"
            ),
            Map.of(
                "id", 2L,
                "filename", "20241115_142015_def67890.pdf",
                "originalName", "report.pdf",
                "size", 1048576,
                "contentType", "application/pdf",
                "url", "/uploads/20241115_142015_def67890.pdf",
                "uploadTime", "2024-11-15T14:20:15"
            )
        );
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", Map.of(
            "files", files,
            "total", files.size(),
            "page", page,
            "size", size
        ));
        
        return ResponseEntity.ok(response);
    }
}
